﻿// Behaviour properties
var ScreensaverFile = "C:\\Users\\Ben\\AppData\\Local\\Google\\Picasa2\\db3\\saverlist.txt";
var SlideInterval = 10;
var FadeInterval =1500;

// Slideshow Controls
var CurrentIndex;
var MaximumIndex;
var ImageNameArray;
var CurrentImage = imageOne;
var SlideTimer = null;


// Main function of the gadget, executed when the view is opened.
function onOpen(){
	initialiseSlideshow();
	runSlideshow();
}

// Initialise the slideshow data.
function initialiseSlideshow(){
	ImageNameArray = new Array();
	MaximumIndex = loadImageNames(ScreensaverFile, ImageNameArray);
}

// Load the image file names from a source file into the destination array
// and return the final size of the array.
function loadImageNames(fileName, destArray){
	var file = framework.system.filesystem.OpenTextFile(fileName);
	while (!file.AtEndOfStream){
		destArray.push(file.ReadLine());
	}
	file.close();
	return destArray.length;
}

// Run the main slideshow loop.
function runSlideshow(){
	slideImage();
	if (SlideTimer != null){
		view.clearInterval(SlideTimer)
	}
	SlideTimer = view.setInterval("slideImage()", SlideInterval*1000);
}

// Execute the slide by fading in a new image while fading out the current image.
function slideImage(){
	var oldImage = CurrentImage;
	var newImage = getOtherImage(oldImage);

	newImage.opacity = 0;
	newImage.visible = true;
	newImage.src = getRandomImageName();
	resizeImage(newImage);

  beginAnimation(function() { setElementOpacity(oldImage); },255,0,FadeInterval/3);
	beginAnimation(function() { setElementOpacity(newImage); },0,255,FadeInterval);
  
	CurrentImage = newImage;
}

// Based on the two image controls, return the image not identified by the parameter
function getOtherImage(notThisImage){
	if(imageOne != notThisImage)
		return imageOne;
	else
		return imageTwo;
}

// Retrieve a random image name.
function getRandomImageName(){
	var index = CurrentIndex;

	while(index == CurrentIndex){
		index = Math.floor(Math.random() * (MaximumIndex+1));
	}

	CurrentIndex = index;
	return ImageNameArray[index];
}

function resizeImage(graphic){
  if(graphic.srcheight > view.height || graphic.srcwidth > view.width){
    if(graphic.srcheight/view.height > graphic.srcwidth/view.width){
      graphic.width=Math.floor(graphic.srcwidth*(view.height/graphic.srcheight));
      graphic.height=view.height;
    }
    else{
      graphic.height=Math.floor(graphic.srcheight*(view.width/graphic.srcwidth));
      graphic.width=view.width;
    }
  }
  else{
    graphic.height=graphic.srcheight;
    graphic.width=graphic.srcwidth;
  }
	graphic.x = Math.floor((view.width - graphic.width) / 2);
}

// Set the opacity of the identified element.
function setElementOpacity(element) {
  element.opacity = event.value;
}